import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import User from '@/views/User.vue'
import DashBoard from '@/views/DashBoard.vue'
import Login from '@/views/Login.vue'
import Share from '@/views/Share.vue'
import store from '../store/index'


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/dashboard/home'
  },
  {
    path: '/login',
    component: Login,
  },
  {
    path: '/share',
    component: Share,
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: DashBoard,
    children: [
      {
        path: '/dashboard/home',
        name: 'Home',
        component: Home,
      },
      {
        path: '/dashboard/user/:userId',
        name: 'User',
        component: User,
        props: (route) => {
          return {
            userId: route.params.userId,
            name: route.query.name,
          }
        }
      }
    ],
    beforeEnter(to, from, next) {
      // 只要访问的页面不是 login, 我们都做登录检查
      if (to.path !== '/login') {
        if (store.state.isLogin) {
          next()
        } else {
          next(`/login?redirect=${to.path}`);
        }
      } else {
        next()
      }
    },
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

/*
  当浏览器地址发生变化时

  1. 全局 beforeEach
  2. 组件 beforeRouteUpdate 
  3. 路由配置 beforeEnter
  4. 组件 beforeRouteEnter
  5. 全局 beforeResolve
  6. 全局 beforeEach
  7. 更新 DOM
*/

// router.beforeEach((to, from, next) => {
//   // 只要访问的页面不是 login, 我们都做登录检查
//   if (to.path !== '/login') {
//     if (window.localStorage['isLogin']) {
//       next()
//     } else {
//       next(`/login?redirect=${to.path}`);
//     }
//   } else {
//     next()
//   }
// })

export default router
